package com.sk.cardeal.act.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.dialog.OpenFormDialogFragment;
import com.sk.cardeal.entity.OrderForm;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.TitleView;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/12/25.
 */

@RuntimePermissions
public class UnReachActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.car_num)
    TextView carNum;
    @BindView(R.id.pep_name)
    TextView pepName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.phone_icon)
    ImageView phoneIcon;
    @BindView(R.id.order_time)
    TextView orderTime;
    @BindView(R.id.next)
    ImageView next;
    @BindView(R.id.order_project)
    TextView orderProject;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.get_car)
    TextView getCar;
    @BindView(R.id.open_form)
    TextView openForm;
    @BindView(R.id.normal_ll)
    LinearLayout normalLl;
    @BindView(R.id.ed_note)
    TextView edNote;
    private LoadingDialog loadingDialog;
    private OrderForm orderForm;
    private boolean isChange = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_unreach;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setMyCallBack(this);
        orderForm = getIntent().getParcelableExtra("data");
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        orderTime.setClickable(false);

        pepName.setText(orderForm.getName());
        carNum.setText(orderForm.getCardNumber());
        tvPhone.setText(orderForm.getPhone());
        orderTime.setText(orderForm.getConventionTime());
        orderProject.setText(orderForm.getTypeName());
        edNote.setText(orderForm.getNote());

    }

    @OnClick({R.id.order_time, R.id.save, R.id.phone_icon, R.id.get_car, R.id.open_form})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.get_car:
                Intent intent = new Intent(mContext, GetCarActivity.class);
                startActivity(intent);
                break;
            case R.id.open_form:
                OpenFormDialogFragment openFormDialogFragment = new OpenFormDialogFragment();
                openFormDialogFragment.setMyCallBack(UnReachActivity.this);
                openFormDialogFragment.show(getSupportFragmentManager(), "open");
                break;
            case R.id.order_time:
                DatePickDialog dialog = new DatePickDialog(this);
                //设置上下年分限制
                dialog.setYearLimt(5);
                //设置标题
                dialog.setTitle("选择进场日期");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        orderTime.setText(MyUtils.stampToDate(date.getTime()));
                    }
                });
                dialog.show();
                break;
            case R.id.save:
                loadingDialog.show();
                AppApi.changeOrderState(orderForm.getId(), 1, orderTime.getText().toString(), UnReachActivity.this, 1, UnReachActivity.this);
                break;
            case R.id.phone_icon:
                UnReachActivityPermissionsDispatcher.startCallWithPermissionCheck(UnReachActivity.this);
                break;
        }
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                setResult(RESULT_OK);
                finish();
                break;

            case 3:
                if (save.getVisibility() == View.VISIBLE) {
                    next.setVisibility(View.GONE);
                    save.setVisibility(View.GONE);
                    orderTime.setClickable(false);
                } else {
                    next.setVisibility(View.VISIBLE);
                    save.setVisibility(View.VISIBLE);
                    orderTime.setClickable(true);
                }

                break;

        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                isChange = true;
                next.setVisibility(View.GONE);
                save.setVisibility(View.GONE);
                orderTime.setClickable(false);
                SnackUtils.show(mRootView, "修改成功！");
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }


    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + tvPhone.getText().toString());
        intent.setData(data);
        startActivity(intent);
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        SnackUtils.showError(mRootView, "您拒绝了电话权限！");
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止app使用您的电话,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UnReachActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @Override
    public void clickView(int id) {
        switch (id) {
            case R.id.beauty_ll:
                Intent beautyIntent = new Intent(mContext, BeautyActivity.class);
                startActivity(beautyIntent);
                break;
            case R.id.fix_ll:
                Intent fixIntent = new Intent(mContext, FixActivity.class);
                startActivity(fixIntent);
                break;
        }
    }
}
